<template>
  <div id="app">
    <!--使用需要的组建，可以引入多个-->
	  <router-view></router-view>
	  <div v-transfer-dom>
		  <alert v-model="show" title="恭喜" @on-show="onShow" @on-hide="onHide"> 绑定成功！ </alert>
	  </div>
  </div>
</template>

<script>
  //导入需要的组建，可以导入多个组建
  import {TransferDomDirective as TransferDom, Alert} from 'vux'
  import NetWorking from '../../utils/networking'
  import CmnUtils from '../../utils/cmnutils'

  export default {
    name: 'app',
    components: {
      //将需要的组建注册进来
	    Alert
    },
	  directives: {
		  TransferDom
	  },
	  data() {
    	return {
		    show: false
	    }
	  },
	  created (){
		  let _this = this
		  this.$store.commit('FETCH_TOKEN')
		  this.$store.commit('FETCH_LAST_LOGIN_AS')
		  let bindWxOpenIdUrl = window.location.origin + '/proxy' + window.location.hash
		  if(bindWxOpenIdUrl.indexOf('openId=') != -1){
			  let args = CmnUtils.getQueryStringArgs(bindWxOpenIdUrl)
			  _this.bindWxOpenId(args.openId)
		  }else{
			  _this.validateToken()
		  }
	  },
	  methods: {
		  onHide () {
			  console.log('on hide')
			  if(this.$store.state.user.lastLoginAs == 'consultant'){
				  location.replace('/mavinSales')
			  }else{
				  location.replace('/mavinTeacher')
			  }
		  },
		  onShow () {
			  console.log('on show')
		  },
		  bindWxOpenId(openId){
		  	let _this = this
    		NetWorking.doPost(
    			'auth/bindWxOpenId',
			    null,
			    null,
			    {
			    	params: {
			    		openId: openId
				    }
			    }
		    ).then(
		    	response => {
		    		let rs = response.data
				    if(rs.error_code == 0){
					    _this.$store.commit('FETCH_USER_MODEL')
					    let userModel = _this.$store.state.user.userModel
					    userModel.sysUser.wx_open_id = openId
					    _this.$store.commit('CREATE_USER_MODEL', userModel)
					    _this.show = true
				    }else{
		    			alert('bindWxOpenId failed')
				    }
			    }
		    )
	    },
    	validateToken(){
		  	let _this = this
		    if(this.$store.state.user.token != null) {
			    NetWorking.doGet(
				    'auth/checkToken',
				    null,
				    null,
			    ).then(
				    response => {
					    let rs = response.data
					    if (rs.error_code == 0) {
						    if(_this.$store.state.user.lastLoginAs == 'teacher'){
							    location.replace('/mavinTeacher')
						    }else if(_this.$store.state.user.lastLoginAs == 'consultant'){
							    location.replace('/mavinSales')
						    }else{
							    this.$store.commit('DELETE_TOKEN')
							    this.$store.commit('DELETE_LAST_LOGIN_AS')
							    location.replace('/login')
						    }
					    } else {
						    location.replace('/login')
					    }
				    }
			    )
		    }else{
			    location.replace('/login')
		    }
	    }
	  }
  }
</script>

<style scoped>

</style>
